package com.cat.dataStructure03;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/remove-k-balanced-substrings/
 * @create 2025/11/6 19:30
 * @since JDK17
 */

public class Solution11 {
    public String removeSubstring(String s, int k) {
        List<int[]> stack = new ArrayList<>();
        for (char x : s.toCharArray()) {
            if (!stack.isEmpty() && stack.getLast()[0] == x) {
                stack.getLast()[1]++;
            } else {
                stack.addLast(new int[]{x, 1});
            }
            if (x == ')' && stack.size() > 1 && stack.getLast()[1] >= k && stack.get(stack.size() - 2)[1] >= k) {
                stack.removeLast(); // 可以把最后一个删除
                if (stack.getLast()[1] == k) {  // 刚刚好消完
                    stack.removeLast();
                } else {
                    stack.getLast()[1] -= k;
                }
            }
        }
        StringBuilder ans = new StringBuilder();
        for (var t : stack) {
            ans.repeat(t[0], t[1]);
        }
        return ans.toString();
    }
}
